package org.company.earth.util;

import java.text.SimpleDateFormat;

import org.company.earth.exception.BaseException;

import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;


public class JsonUtil {
	
	private ObjectMapper NOTNULL_MAPPER = null;
	
	private ObjectMapper DEFAULT_MAPPER = null;
	
	private JsonUtil() {
		DEFAULT_MAPPER = new ObjectMapper();
		
		NOTNULL_MAPPER = new ObjectMapper();
		NOTNULL_MAPPER.setSerializationInclusion(Include.NON_NULL);
		NOTNULL_MAPPER.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
	}
	
	private static JsonUtil instance = null;
	
	public static JsonUtil getInstance() {
		if(instance == null) {
			instance = new JsonUtil();
		}
		return instance;
	}
	
	public<T> String parserNotNull(T t) throws BaseException {
		return this.parser(NOTNULL_MAPPER, t);
	}
	
	public<T> String parser(T t) throws BaseException {
		return this.parser(DEFAULT_MAPPER, t);
	}
	
	private<T> String parser(ObjectMapper mapper,T t) throws BaseException {
		try {
			return mapper.writeValueAsString(t);
		} catch (Exception e) {
			throw new BaseException(560, "json数据序列化异常",e);
		}
	}
	
	public<T> T readValueNotNull(String jsonStr,Class<T> clazz) throws BaseException {
		return this.readValue(NOTNULL_MAPPER, clazz, jsonStr);
	}
	
	public<T> T readValue(String jsonStr,Class<T> clazz) throws BaseException {
		return this.readValue(DEFAULT_MAPPER, clazz, jsonStr);
	}
	
	private<T> T readValue(ObjectMapper mapper,Class<T> clazz,String jsonStr) throws BaseException {
		try {
			return mapper.readValue(jsonStr, clazz);
		} catch (Exception e) {
			throw new BaseException(560, "json数据反序列化异常",e);
		} 
	}
	
	public ObjectNode createNode() {
		return DEFAULT_MAPPER.createObjectNode();
	}
	
	public ArrayNode createArray() {
		return DEFAULT_MAPPER.createArrayNode();
	}
}
